package com.fubowen.lepton

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.WindowInsets
import android.webkit.URLUtil
import android.widget.LinearLayout
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.WindowCompat
import androidx.datastore.preferences.preferencesDataStore
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.NavHostFragment
import com.fubowen.lepton.bean.VisitedBean
import com.fubowen.lepton.conf.SiteConfigViewModel
import com.fubowen.lepton.databinding.ActivityMainBinding
import com.fubowen.lepton.helper.AppConfigHelper
import com.fubowen.lepton.helper.DBHelper
import com.fubowen.lepton.theme.ThemeViewModel
import com.fubowen.lepton.ui.home.HomeFragmentDirections
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private lateinit var viewModel: SiteConfigViewModel
    private lateinit var themeViewModel: ThemeViewModel
    private lateinit var host: NavHostFragment
    private val Context.dataStore by preferencesDataStore(name = "settings")

    override fun onCreate(savedInstanceState: Bundle?) {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        super.onCreate(savedInstanceState)
        AppConfigHelper.init(this)
        savedInstanceState ?: DBHelper.init(this, dataStore)
        viewModel = ViewModelProvider(this)[SiteConfigViewModel::class.java]
        themeViewModel = ViewModelProvider(this)[ThemeViewModel::class.java]
        binding = ActivityMainBinding.inflate(layoutInflater)
        supportActionBar?.hide()
        initSystemBar()
        initIntent()
        initSoftKeyboard()
        initCleaner()
        setContentView(binding.root)
    }

    private fun initSoftKeyboard() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            binding.root.setOnApplyWindowInsetsListener { v, insets ->
                val isVisible = insets.isVisible(WindowInsets.Type.ime())
                if (isVisible) {
                    val inset = insets.getInsets(WindowInsets.Type.ime())
                    viewModel.setKeyboardState(true, inset.bottom)
                }
                insets
            }
        } else {
            binding.root.setOnSystemUiVisibilityChangeListener {

            }
        }
    }

    private fun initSystemBar() {
        val controller = WindowCompat.getInsetsController(window, binding.root)
        controller.isAppearanceLightStatusBars = resources.configuration.uiMode != 0x21
        window.statusBarColor = Color.TRANSPARENT
    }

    private fun initIntent() {
        when (intent.action) {

            Intent.ACTION_SEND -> {

                when (intent.type) {
                    "text/plain" -> {
                        val text = intent.getStringExtra(Intent.EXTRA_TEXT)
                        if (text.isNullOrBlank()) {
                            return
                        }
                        if (URLUtil.isValidUrl(text)) {
                            HomeFragmentDirections.actionHomeFragmentToSearchListItemDetailFragment(
                                "",
                                text
                            ).apply {
                                host.navController.navigate(this)
                            }
                        }
                    }
                }
            }
        }
    }

    private fun initCleaner() {

        CoroutineScope(Dispatchers.IO).launch {
            val ttl = DBHelper.db.settingDao().get(VisitedBean.TTL)?.toLong()
            if (ttl == null || ttl == -1L) {
                return@launch
            }
            val diff = System.currentTimeMillis() - ttl
            DBHelper.db.visitedDao().del(diff)
        }
    }
}
